package com.xgpro.mobile.studycentre.controller;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiFileUploadSingleRequest;
import com.dingtalk.api.request.OapiGetJsapiTicketRequest;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiFileUploadSingleResponse;
import com.dingtalk.api.response.OapiGetJsapiTicketResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.FileItem;
import com.taobao.api.internal.util.WebUtils;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.results.ResponseResult;
import com.xgpro.common.utils.ReadPropertiesUtil;
import com.xgpro.common.utils.TimeUtil;
import com.xgpro.domain.rolemanage.entity.Token;
import com.xgpro.pc.rolemanage.service.TokenService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/DingPan")
@CrossOrigin(allowCredentials = "true")
public class DingPanController {
    @Resource
    private TokenService tokenService;


    @RequestMapping("/getMediaIdFromDing")
    @CrossOrigin(allowCredentials = "true")
    public Object getMediaIdFromDing(@RequestBody Map<String, Object> requestJson) throws Exception {
        String file = (String) requestJson.get("file");
        String fileLenStr = (String) requestJson.get("fileLen");
        String agentId = (String) requestJson.get("agentId");
        String appKey = (String) requestJson.get("appKey");
        String appSecret = (String) requestJson.get("appSecret");
        Map map = new HashMap();
        map.put("result", "0");
        Long fileLen = 0L;
        if (file == null || "".equals(file)) {

            return map;
        }
        if (fileLenStr != null && !"".equals(fileLenStr)) {
            fileLen = Long.parseLong(fileLenStr);
        }
        if (agentId == null || "".equals(agentId)) {

            return map;
        }
        String downloadPath = ReadPropertiesUtil.readUrl("uploadFolder");

        String accessToken = null;
        String ddticket = null;
        Token token = tokenService.findToken();
        if (token.getDate() != null && token.getToken() != null&& token.getTicket() != null) {
            if ((new Date().getTime() - token.getDate().getTime()) <= (105 * 60 * 1000)) {
                accessToken = token.getToken();
                ddticket = token.getTicket();
            } else {
                DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
                OapiGettokenRequest request = new OapiGettokenRequest();
                request.setAppkey(appKey);
                request.setAppsecret(appSecret);
                request.setHttpMethod("GET");
                OapiGettokenResponse response = client.execute(request);
                accessToken = response.getAccessToken();

                DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
                OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
                req.setTopHttpMethod("GET");
                OapiGetJsapiTicketResponse execute = client1.execute(req, accessToken);
                ddticket = execute.getTicket();
                tokenService.updateticket(new Date(), accessToken,ddticket);

            }
        } else {
            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKey);
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            accessToken = response.getAccessToken();

            DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
            OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
            req.setTopHttpMethod("GET");
            OapiGetJsapiTicketResponse execute = client1.execute(req, accessToken);
            ddticket = execute.getTicket();
            tokenService.updateticket(new Date(), accessToken,ddticket);
        }

        OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
        request.setFileSize(fileLen);
        request.setAgentId(agentId);
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?"
                + WebUtils.buildQuery(request.getTextParams(), "utf-8"));
        // 必须重新new一个请求
        request = new OapiFileUploadSingleRequest();
        request.setFile(new FileItem(file));
        OapiFileUploadSingleResponse response = client.execute(request, accessToken);
        String mediaId = response.getMediaId();
        map.put("result", "1");
        map.put("mediaId", mediaId);
        return ResponseResult.ok(map);
    }

    // 钉钉鉴权


    // 支持json传输必须使用该注解
//    @ResponseBody
    @RequestMapping("/getPermFromDing")
    @CrossOrigin(allowCredentials = "true")
    public ResponseResult getPermFromDing(@RequestBody Map<String, Object> requestJson) throws Exception {
        String url = (String) requestJson.get("url");
        String nonce = (String) requestJson.get("nonce");
        String agentId = (String) requestJson.get("agentId");
        String appKey = (String) requestJson.get("appKey");
        String appSecret = (String) requestJson.get("appSecret");
        Map map = new HashMap();
        map.put("result", "0");
        Long fileLen = 0L;

        if (agentId == null || "".equals(agentId)) {

            return ResponseResult.failure(ResultCodeEnum.NO_AGENTID.getCode(), ResultCodeEnum.NO_AGENTID.getMessage());
        }

        String accessToken = null;
        String ddticket = null;
        Token token = tokenService.findTokenTicket();
        if (token.getDate() != null && token.getToken() != null&& token.getTicket() != null) {
            if ((new Date().getTime() - token.getDate().getTime()) <= (105 * 60 * 1000)) {
                accessToken = token.getToken();
                ddticket = token.getTicket();
            } else {
                DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
                OapiGettokenRequest request = new OapiGettokenRequest();
                request.setAppkey(appKey);
                request.setAppsecret(appSecret);
                request.setHttpMethod("GET");
                OapiGettokenResponse response = client.execute(request);
                accessToken = response.getAccessToken();

                DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
                OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
                req.setTopHttpMethod("GET");
                OapiGetJsapiTicketResponse execute = client1.execute(req, accessToken);
                ddticket = execute.getTicket();
                tokenService.updateticket(new Date(), accessToken,ddticket);

            }
        } else {
            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKey);
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            accessToken = response.getAccessToken();

            DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
            OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
            req.setTopHttpMethod("GET");
            OapiGetJsapiTicketResponse execute = client1.execute(req, accessToken);
            ddticket = execute.getTicket();
            tokenService.updateticket(new Date(), accessToken,ddticket);
        }


        Long timeStamp = new Date().getTime();
        String s = String.valueOf(timeStamp);
//        String testurl="http://47.110.33.164:8080/app/index.html?dd_nav_bgcolor=FF3A7BE8";
        String plain = "jsapi_ticket=" + ddticket + "&noncestr=" + nonce + "&timestamp=" + s
                + "&url=" + url;
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        sha1.reset();
        sha1.update(plain.getBytes("UTF-8"));
        String signature = TimeUtil.bytesToHex(sha1.digest());
        map.put("result", "1");
        map.put("timeStamp", timeStamp);
        map.put("signature", signature);
        return ResponseResult.ok(map);

    }
}
